package server;

import interfaces.TaskI;

import java.io.*;
import java.net.*;
import model.Master;

//Thread bzw. Runnable zur Realisierung der Client-Anforderungen
/**
 * Thread to realize the Clientrequest
 *
 * @param <IN>
 * @param <OUT>
 */
class Handler<IN, OUT> implements Runnable { // or 'extends Thread'
	private final Socket client;
	private final ServerSocket serverSocket;

	Handler(ServerSocket serverSocket, Socket client) { // Server/Client-Socket
		this.client = client;
		this.serverSocket = serverSocket;
	}

	public void run() {
		StringBuffer sb = new StringBuffer();
		PrintWriter out = null;
		ObjectInputStream ois;
		ObjectOutputStream oos;
		OUT dataOut = null;
		IN dataIn = null;
		try {
			System.out.println("Server:running service, "
					+ Thread.currentThread());
			out = new PrintWriter(client.getOutputStream(), true);
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(client.getInputStream()));
			char[] buffer = new char[100];
			int anzahlZeichen = bufferedReader.read(buffer, 0, 100); 
			String nachricht = new String(buffer, 0, anzahlZeichen);
			System.out.println("Server:" + nachricht);

			oos = new ObjectOutputStream(client.getOutputStream());


			TaskI t = Master.getTask();
			// TODO while(true)
			// String k="test";
			oos.writeObject(t);
			//oos.flush();
			dataIn = (IN) Master.getInitialData();

			if (!(dataIn == null)) {
				//System.out.println("Server:" + dataIn);
				oos.writeObject(dataIn);
				//oos.flush();
			}

			//
			boolean solution = false;
			ois = new ObjectInputStream(client.getInputStream());// TODO
			// shutdown
			// firsttime
			// error
			
			while (!solution) {
				// if (ois.available() > 0) {
				try {
					dataOut = (OUT) ois.readObject();
					Master.result.send((OUT) dataOut);
					// System.out.println("server:Result=" + dataOut);
					dataIn = (IN) Master.getInitialData();
					if (!(dataIn == null)) {
						//System.out.println("Server:" + dataIn);
						oos.writeObject(dataIn);
						oos.flush();
						dataIn = null;
					} else {
						solution = true;
						oos.writeObject("empty");
						System.out.println("Server: No more InputData");
						oos.flush();
					}

					dataOut = null;

				} catch (ClassNotFoundException e) {
					System.out
							.println("Server:ClassNotFoundException,Return Value|(OUT) ois.readObject()|");
					e.printStackTrace();
				}
			}
			// }
			ois.close();
			oos.close();

			if (!serverSocket.isClosed()) {
				System.out
						.println("Server:--- Ende ServerHandler:ServerSocket close");
				try {
					serverSocket.close();
				} catch (IOException e) {
				}
			}

		} catch (IOException e) {
			System.out.println("Server:IOException, Handler-run");
		} finally {
			if (!client.isClosed()) {
				System.out.println("Server:****** Handler:Client close");
				try {
					client.close();
				} catch (IOException e) {
					System.out.println("Server:****** Handler:Client close");
				}
			}
		}

	}
}